<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位等级" prop="positionLevel">
        <el-select v-model="queryParams.positionLevel" placeholder="请选择岗位等级" clearable>
          <el-option
            v-for="dict in dict.type.position_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="政治面貌" prop="politicalStatus">
        <el-select v-model="queryParams.politicalStatus" placeholder="请选择政治面貌" clearable>
          <el-option
            v-for="dict in dict.type.political_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否免费师范生" prop="isFreeNormalStudent" label-width="120">
        <el-select v-model="queryParams.isFreeNormalStudent" placeholder="请选择是否免费师范生" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="职称" prop="professionalTitle">
        <el-select v-model="queryParams.professionalTitle" placeholder="请选择职称" clearable>
          <el-option
            v-for="dict in dict.type.professional_title"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任课科目" prop="subject">
        <el-input
          v-model="queryParams.subject"
          placeholder="请输入任课科目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借调" prop="isOnLoan">
        <el-select v-model="queryParams.isOnLoan" placeholder="请选择借调" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['teach:teacher:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleLink"
          v-hasPermi="['teach:teacher:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teach:teacher:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teach:teacher:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['teach:teacher:import']"
        >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['teach:teacher:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column label="序号" type="index" width="50" align="center" fixed>
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="教师ID" align="center" prop="teacherId" /> -->
      <el-table-column label="姓名" align="center" prop="teacherName" fixed/>
      <el-table-column label="照片" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="出生年月" align="center" prop="birthDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phone"  width="150"/>
      <el-table-column label="参加工作时间" align="center" prop="hireDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.hireDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进入我校时间" align="center" prop="entryDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.entryDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="现任职岗位" align="center" prop="currentPosition" width="200"/>
      <el-table-column label="岗位等级" align="center" prop="positionLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.position_level" :value="scope.row.positionLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="政治面貌" align="center" prop="politicalStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.political_status" :value="scope.row.politicalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="入党时间" align="center" prop="joinPartyDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.joinPartyDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="籍贯" align="center" prop="hometown"  width="300"/>
      <el-table-column label="身份证号码" align="center" prop="idCard" width="180"/>
      <!-- <el-table-column label="第一学历" align="center" prop="firstDegree" />
      <el-table-column label="第一学历毕业学校" align="center" prop="firstDegreeInstitution" />
      <el-table-column label="第一学历毕业时间" align="center" prop="firstDegreeGraduationDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.firstDegreeGraduationDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="第一学历专业" align="center" prop="firstDegreeMajor" />
      <el-table-column label="最高学历" align="center" prop="highestDegree" />
      <el-table-column label="最高学历毕业学校" align="center" prop="highestDegreeInstitution" />
      <el-table-column label="最高学历毕业时间" align="center" prop="highestDegreeGraduationDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.highestDegreeGraduationDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最高学历专业" align="center" prop="highestDegreeMajor" /> -->
      <el-table-column label="是否免费师范生" align="center" prop="isFreeNormalStudent">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isFreeNormalStudent"/>
        </template>
      </el-table-column>
      <el-table-column label="职称" align="center" prop="professionalTitle">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.professional_title" :value="scope.row.professionalTitle"/>
        </template>
      </el-table-column>
      <el-table-column label="评审时间" align="center" prop="professionalReviewDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.professionalReviewDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="聘用时间" align="center" prop="professionalEmployDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.professionalEmployDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任教科目" align="center" prop="professionalTeachingSubject" />
      <el-table-column label="教师资格种类" align="center" prop="teachingQualification" />
      <el-table-column label="教师资格科目" align="center" prop="teachingSubject" />
      <el-table-column label="原工作单位" align="center" prop="transferFromInstitution" />
      <el-table-column label="调配单位" align="center" prop="transferToInstitution" />
      <el-table-column label="调配时间" align="center" prop="transferDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transferDate, '{y}.{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批准部门" align="center" prop="transferApprovalDepartment" />
      <el-table-column label="任课年级" align="center" prop="grade" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.teacher_grade" :value="scope.row.grade"/>
        </template>
      </el-table-column>
      <el-table-column label="任课科目" align="center" prop="subject" />
      <el-table-column label="周工作量（节）" align="center" prop="weeklyWorkload" width="120"/>
      <el-table-column label="其他岗位" align="center" prop="otherPositions" />
      <el-table-column label="借调" align="center" prop="isOnLoan">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isOnLoan"/>
        </template>
      </el-table-column>
      <el-table-column label="原单位" align="center" prop="originalInstitution" />
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}.{m}.{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}.{m}.{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teach:teacher:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['teach:teacher:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教师管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="100px">
        <TitleDivider title="基本信息"></TitleDivider>
        <el-form-item label="姓名" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="请输入姓名" :maxlength="50" :style="{width: '220px'}"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别"  :style="{width: '220px'}">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" :maxlength="11" :style="{width: '220px'}"/>
        </el-form-item>
        <el-form-item label="身份证号码" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号码" :maxlength="18" :style="{width: '220px'}"/>
        </el-form-item>
        <el-form-item label="出生年月" prop="birthDate">
          <el-date-picker clearable
                          v-model="form.birthDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择出生年月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参加工作时间" prop="hireDate">
          <el-date-picker clearable
                          v-model="form.hireDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择参加工作时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="进入我校时间" prop="entryDate">
          <el-date-picker clearable
                          v-model="form.entryDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择进入我校时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="政治面貌" prop="politicalStatus">
          <el-select v-model="form.politicalStatus" placeholder="请选择政治面貌" :style="{width: '220px'}">
            <el-option
              v-for="dict in dict.type.political_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入党时间" prop="joinPartyDate">
          <el-date-picker clearable
                          v-model="form.joinPartyDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择入党时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="现任职岗位" prop="currentPosition">
          <el-input v-model="form.currentPosition" placeholder="请输入现任职岗位" :maxlength="50" :style="{width: '220px'}"/>
        </el-form-item>
        <el-form-item label="岗位等级" prop="positionLevel">
          <el-select v-model="form.positionLevel" placeholder="请选择岗位等级" :style="{width: '220px'}">
            <el-option
              v-for="dict in dict.type.position_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="其他岗位" prop="otherPositions">
          <el-input v-model="form.otherPositions" placeholder="请输入其他岗位" :maxlength="50" :style="{width: '220px'}"/>
        </el-form-item>
        <el-form-item label="借调" prop="isOnLoan">
          <el-select v-model="form.isOnLoan" placeholder="请选择借调" :style="{width: '220px'}">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原单位" prop="originalInstitution">
          <el-input v-model="form.originalInstitution" placeholder="请输入原单位" :maxlength="100" :style="{width: '220px'}"/>
        </el-form-item>
        <el-form-item label="籍贯" prop="hometown">
          <el-input v-model="form.hometown" placeholder="请输入籍贯" :maxlength="300" :style="{width: '220px'}"/>
        </el-form-item>
        <el-form-item label="是否免费师范生" label-width="110px" prop="isFreeNormalStudent">
          <el-select v-model="form.isFreeNormalStudent" placeholder="请选择是否免费师范生">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="照片" prop="avatar">
          <image-upload v-model="form.avatar"/>
        </el-form-item>
        <TitleDivider title="第一学历"></TitleDivider>
        <el-form-item label="学历" prop="firstDegree">
          <el-input v-model="form.firstDegree" placeholder="请输入第一学历" :maxlength="50"/>
        </el-form-item>
        <el-form-item label="毕业学校" prop="firstDegreeInstitution">
          <el-input v-model="form.firstDegreeInstitution" placeholder="请输入毕业学校" :maxlength="50"/>
        </el-form-item>
        <el-form-item label="毕业时间" prop="firstDegreeGraduationDate">
          <el-date-picker clearable
                          v-model="form.firstDegreeGraduationDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择毕业时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="专业" prop="firstDegreeMajor">
          <el-input v-model="form.firstDegreeMajor" placeholder="请输入专业" :maxlength="50"/>
        </el-form-item>
        <TitleDivider title="最高学历"></TitleDivider>
        <el-form-item label="学历" prop="highestDegree">
          <el-input v-model="form.highestDegree" placeholder="请输入学历" :maxlength="50"/>
        </el-form-item>
        <el-form-item label="毕业学校" prop="highestDegreeInstitution">
          <el-input v-model="form.highestDegreeInstitution" placeholder="请输入毕业学校" :maxlength="50"/>
        </el-form-item>
        <el-form-item label="毕业时间" prop="highestDegreeGraduationDate">
          <el-date-picker clearable
                          v-model="form.highestDegreeGraduationDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择毕业时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="专业" prop="highestDegreeMajor">
          <el-input v-model="form.highestDegreeMajor" placeholder="请输入专业" :maxlength="50"/>
        </el-form-item>
        <TitleDivider title="专业技术职务"></TitleDivider>
        <el-form-item label="职称" prop="professionalTitle">
          <el-select v-model="form.professionalTitle" placeholder="请选择职称">
            <el-option
              v-for="dict in dict.type.professional_title"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评审时间" prop="professionalReviewDate">
          <el-date-picker clearable
                          v-model="form.professionalReviewDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择评审时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="聘用时间" prop="professionalEmployDate">
          <el-date-picker clearable
                          v-model="form.professionalEmployDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择聘用时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任教科目" prop="professionalTeachingSubject">
          <el-input v-model="form.professionalTeachingSubject" placeholder="请输入任教科目" :maxlength="50"/>
        </el-form-item>
        <TitleDivider title="教师资格"></TitleDivider>
        <el-form-item label="种类" prop="teachingQualification">
          <el-input v-model="form.teachingQualification" placeholder="请输入种类" :maxlength="200"/>
        </el-form-item>
        <el-form-item label="科目" prop="teachingSubject">
          <el-input v-model="form.teachingSubject" placeholder="请输入科目" :maxlength="50"/>
        </el-form-item>
        <TitleDivider title="交流调配情况"></TitleDivider>
        <el-form-item label="原工作单位" prop="transferFromInstitution">
          <el-input v-model="form.transferFromInstitution" placeholder="请输入原工作单位" :maxlength="100"/>
        </el-form-item>
        <el-form-item label="调配单位" prop="transferToInstitution">
          <el-input v-model="form.transferToInstitution" placeholder="请输入调配单位" :maxlength="100"/>
        </el-form-item>
        <el-form-item label="调配时间" prop="transferDate">
          <el-date-picker clearable
                          v-model="form.transferDate"
                          type="month"
                          value-format="yyyy.MM"
                          placeholder="请选择调配时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="批准部门" prop="transferApprovalDepartment">
          <el-input v-model="form.transferApprovalDepartment" placeholder="请输入批准部门" :maxlength="100"/>
        </el-form-item>
        <TitleDivider title="任课情况"></TitleDivider>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option
              v-for="dict in dict.type.teacher_grade"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入科目" :maxlength="100"/>
        </el-form-item>
        <el-form-item label="周工作量" prop="weeklyWorkload">
          <el-input-number v-model="form.weeklyWorkload" :min="0" :step="1" step-strictly placeholder="请输入周工作量" />&nbsp;&nbsp;&nbsp;&nbsp;节
        </el-form-item>

        <TitleDivider title="授奖情况"></TitleDivider>
        <el-row>
          <div v-for="(award, index) in form.awardList" :key="index">
            <el-form-item label="名称" :prop="`award_name${award.uid}`">
              <el-input v-model="award.award_name" placeholder="请输入名称" @input="check" :maxlength="100"/>
            </el-form-item>
            <el-form-item label="授予部门" :prop="`award_department${award.uid}`">
              <el-input v-model="award.award_department" placeholder="请输入授予部门" @input="check" :maxlength="100"/>
            </el-form-item>
            <el-form-item label="授予时间" :prop="`award_date${award.uid}`">
              <el-date-picker clearable
                              v-model="award.award_date"
                              type="month"
                              value-format="yyyy.MM"
                              placeholder="请选择授予时间" @input="check">
              </el-date-picker>
            </el-form-item>
            <div class="award-btn">
              <i v-if="form.awardList.length > 1" class="el-icon-remove-outline" @click="handleDeleteAward(award)"></i>
              <i v-if="form.awardList.length === index + 1" class="el-icon-circle-plus-outline" @click="handleAddAward()"></i>
            </div>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 教师管理导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的教师数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTeacher, getTeacher, delTeacher, addTeacher, updateTeacher } from "@/api/teach/teacher";
import TitleDivider from '@/components/TitleDivider';
import { getUid } from '@/utils/uid'
import { mapGetters } from 'vuex';
import { getToken } from "@/utils/auth";

export default {
  name: "Teacher",
  components: {
    TitleDivider
  },
  dicts: ['political_status', 'position_level', 'sys_yes_no', 'sys_user_sex', 'professional_title', 'teacher_grade'],
  data() {
    const validateNumber = (rule, value, callback) => {
      if (!value) {
        callback();
        return;
      }
      // 手机 + 固话
      const REG = /^(((0\d{2,3}-)?\d{7,8})|(1[34578]\d{9}))$/;
      if (value && value.trim()) {
        !REG.test(value) ? callback(new Error('您输入的格式不正确，请重新输入！')) : callback();
      } else {
        callback();
      }
    };
    /**
     * 严格验证15位或者18位身份证号码，通过返回空字符串，否则返回相应的错误信息。身份证号为空则不进行验证
     * @cardID 输入身份证号码
     * @return 验证通过返回空字符串，否则返回相应的错误信息
     * @author hailiang.liu@100credit.com
     * @last modify : 2016/6/20
     */
    const checkIDCard = (rule, value, callback) => {
      if (!value) {
        callback();
        return;
      }
      var vcity = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        71: '台湾',
        81: '香港',
        82: '澳门',
        91: '国外'
      };

      // 检查号码是否符合规范，包括长度，类型
      function isCardNo(card) {
        // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
        var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
        if (reg.test(card) === false) {
          return false;
        }
        return true;
      }

      // 取身份证前两位,校验省份
      // var checkProvince = function(card)
      function checkProvince(card) {
        var province = card.substr(0, 2);
        if (vcity[province] == undefined) {
          return false;
        }
        return true;
      }

      // 检查生日是否正确
      function checkBirthday(card) {
        var len = card.length;
        // 身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字
        if (len == '15') {
          var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
          var arr_data = card.match(re_fifteen);
          var year = arr_data[2];
          var month = arr_data[3];
          var day = arr_data[4];
          var birthday = new Date('19' + year + '/' + month + '/' + day);
          return verifyBirthday('19' + year, month, day, birthday);
        }
        // 身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
        if (len == '18') {
          var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
          var arr_data = card.match(re_eighteen);
          var year = arr_data[2];
          var month = arr_data[3];
          var day = arr_data[4];
          var birthday = new Date(year + '/' + month + '/' + day);
          return verifyBirthday(year, month, day, birthday);
        }
        return false;
      }

      // 校验日期
      function verifyBirthday(year, month, day, birthday) {
        var now = new Date();
        var now_year = now.getFullYear();
        // 年月日是否合理
        if (birthday.getFullYear() == year && birthday.getMonth() + 1 == month && birthday.getDate() == day) {
          // 判断年份的范围（3岁到120岁之间)
          var time = now_year - year;
          if (time >= 3 && time <= 120) {
            return true;
          }
          return false;
        }
        return false;
      }

      // 校验位的检测
      function checkParity(card) {
        // 15位转18位
        card = changeFivteenToEighteen(card);
        var len = card.length;
        if (len == '18') {
          var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
          var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
          var cardTemp = 0,
            i,
            valnum;
          for (i = 0; i < 17; i++) {
            cardTemp += card.substr(i, 1) * arrInt[i];
          }
          valnum = arrCh[cardTemp % 11];
          if (valnum == card.substr(17, 1)) {
            return true;
          }
          return false;
        }
        return false;
      }
      // 15位转18位身份证号
      function changeFivteenToEighteen(card) {
        if (card.length == '15') {
          var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
          var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
          var cardTemp = 0,
            i;
          card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
          for (i = 0; i < 17; i++) {
            cardTemp += card.substr(i, 1) * arrInt[i];
          }
          card += arrCh[cardTemp % 11];
          return card;
        }
        return card;
      }
      function checkCard(cardID) {
        var card = cardID;
        var tip = ''; // 不变验证通过
        var pass = true; // 不变验证通过,目前没有用到
        // 是否为空  身份证号为空则不进行验证
        if (card == '' || card == undefined || card == null) {
          /* tip = '身份证号不能为空';
                  pass = false; */
          tip = '';
          pass = true;
        }
        // 校验长度，类型
        else if (isCardNo(card) === false) {
          var reg = /^[0-9]*$/; // 验证数字,非数字出现即为非法字符，上面已经对最后一位X座判断了
          tip = '请输入15/18位证号' + (!reg.test(card) ? '(有非法字符)' : '(目前' + card.length + '位)');
          pass = false;
        }
        // 检查省份
        else if (checkProvince(card) === false) {
          tip = '地区校验错误，请重新输入';
          pass = false;
        }
        // 校验生日
        else if (checkBirthday(card) === false) {
          tip = '生日不正确，请重新输入';
          pass = false;
        }
        // 检验位的检测
        else if (checkParity(card) === false) {
          tip = '校验位错误，请重新输入';
          pass = false;
        }
        return tip;
      }

      const len = value.trim().length;
      if (value) {
        if (len === 0) {
          callback(new Error('身份证号不能为空!'));
        }
        let val = checkCard(value.trim());
        val ? callback(new Error(val)) : callback();
      }
      callback();
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教师管理表格数据
      teacherList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teacherName: null,
        gender: null,
        positionLevel: null,
        politicalStatus: null,
        isFreeNormalStudent: null,
        professionalTitle: null,
        subject: null,
        isOnLoan: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        teacherName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        phone: [
          { required: false,
            validator: validateNumber,
            trigger: 'blur',
            message: '您输入的格式不正确，请重新输入！' }
        ],
        idCard: [
          { validator: checkIDCard, trigger: 'blur' },
          { max: 30, message: '输入值过长！', trigger: 'blur' }
        ],
      },
      // 教师导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的报名数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/teach/teacher/importData"
      },
    };
  },
  computed: {
    ...mapGetters(['name'])
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询教师管理列表 */
    getList() {
      this.loading = true;
      listTeacher(this.queryParams).then(response => {
        this.teacherList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        teacherId: null,
        teacherName: null,
        avatar: null,
        gender: null,
        birthDate: null,
        phone: null,
        hireDate: null,
        entryDate: null,
        currentPosition: null,
        positionLevel: null,
        politicalStatus: null,
        joinPartyDate: null,
        hometown: null,
        idCard: null,
        firstDegree: null,
        firstDegreeInstitution: null,
        firstDegreeGraduationDate: null,
        firstDegreeMajor: null,
        highestDegree: null,
        highestDegreeInstitution: null,
        highestDegreeGraduationDate: null,
        highestDegreeMajor: null,
        isFreeNormalStudent: null,
        professionalTitle: null,
        professionalReviewDate: null,
        professionalEmployDate: null,
        professionalTeachingSubject: null,
        teachingQualification: null,
        teachingSubject: null,
        transferFromInstitution: null,
        transferToInstitution: null,
        transferDate: null,
        transferApprovalDepartment: null,
        grade: null,
        subject: null,
        weeklyWorkload: null,
        otherPositions: null,
        awards: null,
        awardList: [{award_name: null, award_department: null, award_date: null, uid: getUid()}],
        isOnLoan: null,
        originalInstitution: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.teacherId)
      this.names = selection.map(item => item.teacherName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教师管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teacherId = row.teacherId || this.ids
      getTeacher(teacherId).then(response => {
        this.form = response.data;
        this.form.awardList = JSON.parse(this.form.awards || '[]').map(_ => ({..._, uid: getUid()}));
        this.open = true;
        this.title = "修改教师管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.awards = JSON.stringify(this.form.awardList.map(_ => ({award_name: _.award_name, award_department: _.award_department, award_date: _.award_date})) || [])
          if (this.form.teacherId != null) {
            this.form.updateBy = this.name;
            updateTeacher(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createBy = this.name;
            addTeacher(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const teacherName = row.teacherName || this.names;
      const teacherIds = row.teacherId || this.ids;
      this.$modal.confirm('是否确认删除教师管理编号为"' + teacherName + '"的数据项？').then(function() {
        return delTeacher(teacherIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teach/teacher/export', {
        ...this.queryParams
      }, `教师信息_${new Date().getTime()}.xlsx`)
    },
    // handleLink() {
    //   this.$router.push('/teach/teacher-info/add')
    // },
    handleDeleteAward(award) {
      this.form.awardList = this.form.awardList.filter(_ => _.uid !== award.uid)
      this.$forceUpdate(); //强制刷新
    },
    handleAddAward() {
      this.form.awardList.push({award_name: null, award_department: null, award_date: null, uid: getUid()})
      this.$forceUpdate(); //强制刷新
    },
    check(val){
      this.$forceUpdate(); //强制刷新
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "教师导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('teach/teacher/importTemplate', {
      }, `教师导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="scss" scoped>
.award-btn {
  width: 50px;
  height: 36px;
  display: inline-flex;
  align-items: center;
  i {
    padding-right: 8px;
    cursor: pointer;
  }
}
</style>
